import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    ActivityIndicator,
    ListView,
    ScrollView,
    TouchableWithoutFeedback,
    StatusBar,
} from 'react-native';

import {PullList} from 'react-native-pull';
import Video from 'react-native-video';

export default class HomeTab extends Component {

    constructor(props) {
        super(props);
        this.dataSource = [];
        this.state = {
            isFirst: true,
            // 判断视频是否加载完毕
            videoReady: true,
            isPlay: true,
            lists: '',
            isRefresh: true,
            nomore: true,
            list: (new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})).cloneWithRows(this.dataSource),
            tabIndex: 0,
        };
        this.renderHeader = this.renderHeader.bind(this);
        this.renderRow = this.renderRow.bind(this);
        this.renderFooter = this.renderFooter.bind(this);
        this.loadMore = this.loadMore.bind(this);
        this.topIndicatorRender = this.topIndicatorRender.bind(this);
        this.renderNewsItem = this.renderNewsItem.bind(this);
        this.setTime = this.setTime.bind(this);
        this.goPlay = this.goPlay.bind(this);
    }

    componentDidMount(){
        global.HomeTabIndex = this;
        fetch('https://result.eolinker.com/XPZsElz98c92f9c243e2f760bf17420ef24906430bea331?uri=lindf.com',
            {
                method: 'POST',
            }
            )
            .then((response) => response.json())        // json方式解析，如果是text就是 response.text()
            .then((responseData) => {   // 获取到的数据处理
                this.dataSource = responseData.result.shopList;
                this.setState({
                    lists: responseData.result.lists,
                    list: this.state.list.cloneWithRows(this.dataSource),
                });

            })
            .catch((error) => {     // 错误处理
                alert(error);
            })
            .done();
    }

    // 鞋匠资讯
    renderNewsItem() {
        // 数组
        let itemAry = [];
        // 遍历
        let _this = this;
        for (let i = 0; i<this.state.lists.length; i++) {
            itemAry.push(
                <TouchableWithoutFeedback key={i} onPress={() => this.props.navigate('NewsDetail',{
                    id: _this.state.lists[i].id
                })}>
                    <View style={{width: 250, marginRight: 8, paddingBottom: 5}}>
                        <Image style={{
                            width: 250,
                            height: 140,
                            marginRight: 8,
                            marginBottom: 8,
                            borderRadius: 5
                        }} source={{uri: _this.state.lists[i].src}}/>
                        <Text style={{fontSize: 13, lineHeight: 17, color: '#707070'}} numberOfLines={2}>{_this.state.lists[i].text}</Text>
                    </View>
                </TouchableWithoutFeedback>
            )
        }
        return itemAry;
    }

    onPullRelease(resolve) {
        //下拉加载请求接口
        setTimeout(() => {
            resolve();
        }, 3000);
    }

    topIndicatorRender(pulling, pullok, pullrelease) {
        const hide = {position: 'absolute', left: -10000};
        const show = {position: 'relative', left: 0};
        setTimeout(() => {
            if (pulling) {
                this.txtPulling && this.txtPulling.setNativeProps({style: show});
                this.txtPullok && this.txtPullok.setNativeProps({style: hide});
                this.txtPullrelease && this.txtPullrelease.setNativeProps({style: hide});
            } else if (pullok) {
                this.txtPulling && this.txtPulling.setNativeProps({style: hide});
                this.txtPullok && this.txtPullok.setNativeProps({style: show});
                this.txtPullrelease && this.txtPullrelease.setNativeProps({style: hide});
            } else if (pullrelease) {
                this.txtPulling && this.txtPulling.setNativeProps({style: hide});
                this.txtPullok && this.txtPullok.setNativeProps({style: hide});
                this.txtPullrelease && this.txtPullrelease.setNativeProps({style: show});
            }
        }, 1);
        return (
            <View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 60}}>
                <ActivityIndicator size="small" color="gray" style={{marginRight: 5}}/>
                <Text ref={(c) => {
                    this.txtPulling = c;
                }}>下拉刷新...</Text>
                <Text ref={(c) => {
                    this.txtPullok = c;
                }}>释放刷新...</Text>
                <Text ref={(c) => {
                    this.txtPullrelease = c;
                }}>正在刷新...</Text>
            </View>
        );
    }

    render() {
        let barHeight = StatusBar.currentHeight;
        return (
            <View style={{
                flex: 1,
                flexDirection: 'column',
                backgroundColor: '#fff',
                // paddingTop: barHeight
            }}>
                <StatusBar hidden={false} translucent={false} barStyle={'default'} />
                <View style={{
                    flexDirection: 'row',
                    height: 44,
                    backgroundColor: '#FFF',
                    paddingTop: 8,
                    paddingBottom: 8,
                    paddingLeft: 10,
                    paddingRight: 10,
                }}>
                    <View style={{
                        flex: 1,
                        flexDirection: 'row',
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: '#efeff1',
                        borderRadius: 20,
                        marginLeft: 8,
                        marginRight: 8,
                    }}>
                        <Image style={{
                            width: 13,
                            height: 13,
                            marginRight: 8,
                        }} source={require('../../images/Search-Icon.png')}/>
                        <Text style={{fontSize: 13, color: '#707070'}}>搜索</Text>
                    </View>
                    <Image style={{
                        width: 24,
                        height: 20,
                        marginTop: 4
                    }} source={require('../../images/mess.png')}/>
                </View>
                <PullList
                    contentContainerStyle={{
                        flexDirection: 'row',
                        flexWrap:'wrap',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        backgroundColor: '#fff',
                        paddingLeft: 10,
                        paddingRight: 10,
                    }}
                    horizontal={false}
                    numColumns={2}
                    onPullRelease={this.onPullRelease} // 请求接口数据的方法
                    topIndicatorRender={this.topIndicatorRender}
                    topIndicatorHeight={60}
                    renderHeader={this.renderHeader}
                    dataSource={this.state.list}
                    pageSize={5}
                    initialListSize={5}
                    renderRow={this.renderRow}
                    onEndReached={this.loadMore}
                    onEndReachedThreshold={30}
                    renderFooter={this.renderFooter}
                    enableEmptySections={true}
                />
            </View>
        );
    }

    //当视频开始加载时的回调函数
    loadStart(){
        // alert('开始加载...')
    }

    //当视频加载完毕时的回调函数
    setTime(){
        if(this.state.videoReady){
            // alert('加载完成...');
            this.setState({
                videoReady: false
            })
        }
    }

    //当视频播放完毕时的回调函数
    onEnd(){
        alert('播放完成...')
    }

    //当视频不能加载，或出错后的回调函数
    videoError(){
        alert('视频出错...')
    }

    // 播放视频
    goPlay(){
        // alert(1);
        this.setState({
            isPlay: false
        })
    }

    // 滑动时会触发
    renderHeader() {
        // alert('renderHeader');
        let playBtn = this.state.isPlay?
            <TouchableWithoutFeedback onPress={this.goPlay}>
                <Image style={styles.playBtn} source={require('../../images/play.png')}/>
            </TouchableWithoutFeedback>:null;
        return (
            <View style={{width: '100%'}}>
                <View style={{position: 'relative',marginLeft: -10, marginRight: -10,backgroundColor: '#000'}}>
                    <Video
                        style={{width: '100%',height: 210}}
                        // source={require('../../images/summary_hight.mp4')}
                        source={{uri: "http://www.wws666.com/uploadfile/home2.mp4"}}
                        rate={1.0}                   // 控制暂停/播放，0 代表暂停paused, 1代表播放normal.
                        volume={1.0}                 // 声音的放大倍数，0 代表没有声音，就是静音muted, 1 代表正常音量 normal，更大的数字表示放大的倍数
                        muted={false}                // true代表静音，默认为false.
                        paused={this.state.isPlay}      // true代表暂停，默认为false
                        resizeMode="contain"           // 视频的自适应伸缩铺放行为，
                        repeat={false}                // 是否重复播放
                        playInBackground={false}     // 当app转到后台运行的时候，播放是否暂停
                        playWhenInactive={false}     // [iOS] Video continues to play when control or notification center are shown. 仅适用于IOS
                        onLoadStart={this.loadStart} // 当视频开始加载时的回调函数
                        onLoad={this.setDuration}    // 当视频加载完毕时的回调函数
                        onProgress={this.setTime}    //  进度控制，每250ms调用一次，以获取视频播放的进度
                        onEnd={this.onEnd}           // 当视频播放完毕后的回调函数
                        onError={this.videoError}    // 当视频不能加载，或出错后的回调函数
                    />
                    {playBtn}
                </View>
                <View style={{marginLeft: -10, marginRight: -10}}>
                    <View style={{
                        backgroundColor: '#ffffff',
                        paddingLeft: 10,
                        paddingRight: 10,
                        flexDirection: 'row',
                        justifyContent: 'space-between'
                    }}>
                        <Text style={{fontSize: 15, color: '#535353', lineHeight: 45}}>鞋匠资讯</Text>
                        <TouchableWithoutFeedback onPress={() => this.props.navigate('NewsList',{
                            id: 1
                        })}>
                            <View>
                                <Text style={{fontSize: 14, color: '#959595', lineHeight: 45}}>更多+</Text>
                            </View> 
                        </TouchableWithoutFeedback>
                    </View>
                    <ScrollView
                        style={{
                            paddingLeft: 10,
                            backgroundColor: '#FFFFFF'
                        }}
                        horizontal={true}
                        showsHorizontalScrollIndicator={false}
                    >
                        {this.renderNewsItem()}
                    </ScrollView>
                </View>
                <TouchableWithoutFeedback onPress={() => this.props.navigate('PrizeDetail')}>
                    <View style={{marginLeft: -10, marginRight: -10}}>
                        <View style={{position: 'relative',paddingTop: 10,paddingBottom: 10,backgroundColor: '#eeeeee'}}>
                            <Image style={{
                                width: '100%',
                                height: 70
                            }} source={require('../../images/new.png')}/>
                            <View style={{width: '76%', position: 'absolute', right: 10, top: '50%',marginTop: -5}}>
                                <Text numberOfLines={1} style={{fontSize: 13, color: '#181818', lineHeight: 16}}>恭喜 130xxxx9409
                                    用户获得 1300.58元免单！</Text>
                                <Text numberOfLines={1} style={{fontSize: 13, color: '#181818', lineHeight: 16}}>恭喜 130xxxx9409
                                    用户获得 1300.58元免单</Text>
                            </View>
                        </View>
                    </View>
                </TouchableWithoutFeedback>
                <View style={{
                    backgroundColor: '#ffffff',
                    marginLeft: -10,
                    marginRight: -10,
                    paddingLeft: 10,
                    paddingRight: 10,
                    flexDirection: 'row',
                    justifyContent: 'space-between'
                }}>
                    <Text style={{fontSize: 15, color: '#535353', lineHeight: 45}}>推荐代理商品</Text>
                    <Text style={{fontSize: 14, color: '#959595', lineHeight: 45}}>更多+</Text>
                </View>
            </View>

        );
    }

    renderRow(item, sectionID, rowID, highlightRow) {
        return (
            <View style={{
                width: '48.5%',
                backgroundColor: '#fff'
            }} key={item.id}>
                <View style={{paddingBottom: 8}}>
                    <Image style={{
                        width: '100%',
                        height: 125,
                        borderRadius: 5,
                        marginBottom: 5
                    }} source={{uri: item.img}}/>
                    <Text style={{fontSize: 13, lineHeight: 17, color: '#707070'}} numberOfLines={2}>固特异工艺手工鞋 JACK Adass
                        PENG 高级定致 制鞋</Text>
                </View>
            </View>
        );
    }

    // 滑动时会触发
    renderFooter() {
        // alert('renderFooter');
        // if(!this.state.isFirst){
            if (!this.state.nomore) {
                return (
                    <View style={{width: '200%',height: 30,marginLeft: '-50%',flexDirection: 'row', justifyContent: 'center'}}>
                        <Text style={{lineHeight: 30}}>没有更多了</Text>
                    </View>
                );
            } else {
                return (
                    <View style={{width: '200%',marginLeft: '-50%',flexDirection: 'row', justifyContent: 'center'}}>
                        <ActivityIndicator style={{marginRight: 5}}/>
                        <Text style={{lineHeight: 30}}>正在加载...</Text>
                    </View>
                );
            }
        // }
        // else {
        //     this.setState({
        //         isFirst: false
        //     })
        // }

    }

    loadMore() {
        // alert('loadMore');
        if (!this.state.isFirst && this.state.nomore) {
            this.dataSource.push({
                "id":2,
                "title":2161616512651265,
                "img":"http://pic.58pic.com/58pic/13/28/93/67E58PICdF7_1024.jpg"
            });
            // for (var i = 0; i < 5; i++) {
            //     this.dataSource.push({
            //         id: i + 1,
            //         title: `this is`,
            //     })
            // }
            // this.dataSource.push({
            //     id: 6,
            //     title: `finish create data ...`,
            // });
            setTimeout(() => {
                this.setState({
                    list: this.state.list.cloneWithRows(this.dataSource),
                    nomore: false
                });
            }, 1000);
        }
        else {
            this.setState({
                isFirst: false
            })
        }
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#eeeeee',
    },
    playBtn: {
        position: 'absolute',
        left: '50%',
        top: '50%',
        marginLeft: -26,
        marginTop: -26,
        width: 52,
        height: 52
    }
});